import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
// 导入页面组件
const Index = () => import('@/pages/Index')
const List = () => import('@/pages/List')
const Show = () => import('@/pages/Show')
const Login = () => import('@/pages/Login')
const Reg = () => import('@/pages/Reg')
const Add = () => import('@/pages/Add')
const User = () => import('@/pages/User')
const Cate = () => import('@/pages/Cate')
const Layout = () => import('@/pages/Layout')
const UserSc = () => import('@/pages/User/Sc')
const UserArticle = () => import('@/pages/User/Article')
const UserZan = () => import('@/pages/User/Zan')
const UserEdit = () => import('@/pages/User/Edit')
import { gettoken } from '@/utils/storage'
let router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/index',
      children: [
        {
          path: '/index',
          component: Index
        },
        {
          path: '/add',
          component: Add
        },
        {
          path: '/cate',
          component: Cate
        },
        {
          path: '/user',
          component: User,
        },
      ]
    },
    {
      path: '/user/sc',
      component: UserSc,
      meta: { needLogin: true }
    },
    {
      path: '/user/zan',
      component: UserZan,
      meta: { needLogin: true }
    },
    {
      path: '/user/article',
      component: UserArticle,
      meta: { needLogin: true }
    },
    {
      path: '/user/edit',
      component: UserEdit
    },
    {
      path: '/list',
      component: List
    },
    {
      path: '/show',
      component: Show
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/reg',
      component: Reg
    },

  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (gettoken()) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }

})

export default router